import axios from "axios";
import throttle from "lodash/throttle";
import { message } from "antd";
import getCookie from "./cookie.js";
const instance = axios.create({
  baseURL: "",
  timeout: 1000 * 5,
  headers: {
    "X-Requested-With": "XMLHttpRequest",
    "Content-Type": "application/json",
  },
  withCredentials: false, //表示跨域请求时是否需要使用凭证
});
instance.defaults.retry = 2;
instance.defaults.retryDelay = 1000;
instance.defaults.headers.post["Content-Type"] =
  "application/json;charset=UTF-8";

const retryConnect = (obj) => {
  let config = obj.config; //获取错误信息
  if (!config || !config.retry) return Promise.reject(obj);
  config.__retryCount = config.__retryCount || 0;
  if (config.__retryCount >= config.retry) {
    throttle(() => {
      message.error("网络连接失败...");
    }, 1000);
    return Promise.reject(obj);
  }
  //重试次数记录  请求次数记录在请求中  访问次数记录在路由中
  config.__retryCount += 1;
  let retryPromise = new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, config.retryDelay || 1);
  });
  return retryPromise.then(() => {
    return instance(config);
  });
};
instance.interceptors.request.use(
  (config) => {
    let token = getCookie.get("token");
    token && (config.headers.Authorization = token);
    if (config.data instanceof FormData) {
      //处理文件格式的请求  文件上传
      config.headers["Content-Type"] = "multipart/form-data;charset=UTF-8";
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);
instance.interceptors.response.use(
  (response) => {
    return Promise.resolve(response.data);
  },
  (error) => {
    return retryConnect(error);
  },
);
const downFile = (url, params) => {
  // get 是 params   post 是data
  // content-disposition = attachment; filename=report.xlsx  这类格式的  不走重试
  return axios
    .request({
      responseType: "blob",
      ...params,
      url,
    })
    .then((response) => {
      // 从响应头获取文件名
      const disposition = response.headers["content-disposition"];
      let filename = "file";
      if (disposition) {
        // 处理UTF-8编码的文件名
        const utf8Filename = disposition.match(/filename\*=UTF-8''([^;]+)/i);
        if (utf8Filename) {
          filename = decodeURIComponent(utf8Filename[1]);
        } else {
          const match = disposition.match(/filename="?([^;"]+)"?/i);
          if (match) {
            filename = match[1];
          }
        }
      }
      if (response.data instanceof Blob) {
        return {
          fileName: filename,
          fileData: response.data,
        };
      } else {
        message.error("下载失败");
      }
    });
};

instance.all = axios.all;
instance.spread = axios.spread;
instance.downFile = downFile;
export default instance;
